<template>
	<view class="chat-detail">
		<!-- 聊天消息列表 -->
		<scroll-view 
			class="message-list" 
			scroll-y="true" 
			:scroll-top="scrollTop"
			scroll-with-animation="true"
		>
			<view 
				class="message-item" 
				v-for="(message, index) in messageList" 
				:key="index"
				:class="{ 'own-message': message.isOwn }"
			>
				<view class="avatar">
					<view class="avatar-default" v-if="!message.avatar || message.avatar === ''">{{ message.isOwn ? '我' : '我们' }}</view>
					<image v-else :src="message.avatar" mode="aspectFill"></image>
				</view>
				<view class="message-content">
					<view 
						class="message-bubble" 
						:class="{ 'own-bubble': message.isOwn }"
					>
						<text>{{ message.content }}</text>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 输入区域 -->
		<view class="input-section">
			<view class="input-bar">
				<view class="voice-btn">
					<image src="/static/chat-detail/yuyin.svg" mode="aspectFit"></image>
				</view>
				<view class="input-container">
					<input 
						class="message-input"
						v-model="inputMessage"
						placeholder=""
						@confirm="sendMessage"
						confirm-type="send"
					/>
				</view>
				<view class="emoji-btn">
					<image src="/static/chat-detail/biaoqing.svg" mode="aspectFit"></image>
				</view>
				<view class="more-btn">
					<image src="/static/chat-detail/jiahao.svg" mode="aspectFit"></image>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, nextTick, onMounted, onUnmounted } from 'vue'

// 获取页面参数
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
const chatId = currentPage.options.id
const chatName = currentPage.options.name

// 设置导航栏标题
uni.setNavigationBarTitle({
	title: decodeURIComponent(chatName || '聊天')
})

// 响应式数据
const inputMessage = ref('')
const scrollTop = ref(0)

// 缓存key
const CHAT_CACHE_KEY = `chat_messages_${chatId}`
const CHAT_LIST_CACHE_KEY = 'chat_list'

// 从缓存中加载聊天消息
const loadMessagesFromCache = () => {
	try {
		const cachedMessages = uni.getStorageSync(CHAT_CACHE_KEY)
		if (cachedMessages && Array.isArray(cachedMessages)) {
			return cachedMessages
		}
	} catch (error) {
		console.error('加载聊天记录失败:', error)
	}
	// 返回默认消息
	return [
		{
			id: 1,
			content: '你好！我是我们51，有什么可以帮助你的吗？',
			isOwn: false,
			avatar: '/static/avatar/robot.jpg',
			time: '10:30'
		}
	]
}

// 保存消息到缓存
const saveMessagesToCache = (messages) => {
	try {
		uni.setStorageSync(CHAT_CACHE_KEY, messages)
	} catch (error) {
		console.error('保存聊天记录失败:', error)
	}
}

// 更新聊天列表中的最后消息
const updateChatListLastMessage = (lastMessage, time) => {
	try {
		let chatListData = uni.getStorageSync(CHAT_LIST_CACHE_KEY) || []
		
		// 查找当前聊天
		const chatIndex = chatListData.findIndex(chat => chat.id == chatId)
		if (chatIndex !== -1) {
			// 更新最后消息和时间
			chatListData[chatIndex].lastMessage = lastMessage
			chatListData[chatIndex].time = time
		} else {
			// 如果不存在，创建新的聊天项
			chatListData.push({
				id: parseInt(chatId),
				name: decodeURIComponent(chatName),
				avatar: '/static/avatar/robot.jpg',
				lastMessage: lastMessage,
				time: time,
				unread: 0
			})
		}
		
		// 保存到缓存
		uni.setStorageSync(CHAT_LIST_CACHE_KEY, chatListData)
		
		// 通知聊天列表页面更新
		uni.$emit('chatListUpdate', chatListData)
	} catch (error) {
		console.error('更新聊天列表失败:', error)
	}
}

// 消息列表
const messageList = ref(loadMessagesFromCache())

// 自动回复话术库
const autoReplies = [
	'哈哈哈，你说得对！',
	'好的呢～',
	'我觉得也是',
	'确实如此',
	'有道理',
	'不错不错',
	'真的吗？',
	'太棒了！',
	'我也这么想',
	'好主意！',
	'收到～',
	'明白了',
	'没问题',
	'可以的',
	'好呀好呀',
	'哈哈哈哈',
	'这个我喜欢',
	'赞同！',
	'就是这样',
	'说得很对'
]

// 发送消息
const sendMessage = () => {
	if (!inputMessage.value.trim()) return
	
	const currentTime = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
	
	// 添加用户消息
	const userMessage = {
		id: Date.now(),
		content: inputMessage.value,
		isOwn: true,
		avatar: '/static/avatar/group.jpg',
		time: currentTime
	}
	
	messageList.value.push(userMessage)
	
	// 保存到缓存
	saveMessagesToCache(messageList.value)
	
	// 更新聊天列表中的最后消息
	updateChatListLastMessage(inputMessage.value, '刚刚')
	
	inputMessage.value = ''
	
	// 滚动到底部
	scrollToBottom()
	
	// 模拟对方自动回复
	setTimeout(() => {
		const randomReply = autoReplies[Math.floor(Math.random() * autoReplies.length)]
		const replyTime = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
		const replyMessage = {
			id: Date.now() + 1,
			content: randomReply,
			isOwn: false,
			avatar: '/static/avatar/robot.jpg',
			time: replyTime
		}
		
		messageList.value.push(replyMessage)
		
		// 保存到缓存
		saveMessagesToCache(messageList.value)
		
		// 更新聊天列表中的最后消息
		updateChatListLastMessage(randomReply, '刚刚')
		
		scrollToBottom()
	}, 1000 + Math.random() * 2000) // 1-3秒随机延迟
}

// 滚动到底部
const scrollToBottom = () => {
	nextTick(() => {
		scrollTop.value = scrollTop.value === 999999 ? 999998 : 999999
	})
}

onMounted(() => {
	scrollToBottom()
})

// 页面卸载时保存数据
onUnmounted(() => {
	saveMessagesToCache(messageList.value)
})
</script>

<style scoped>
.chat-detail {
	height: 100vh;
	display: flex;
	flex-direction: column;
	background-color: #ededed;
	position: relative;
}

.message-list {
	flex: 1;
	padding: 16px;
	padding-bottom: 80px; /* 给输入框预留空间 */
	box-sizing: border-box;
}

.message-item {
	display: flex;
	align-items: flex-start;
	margin-bottom: 16px;
	padding: 0 8px; /* 添加左右内边距 */
}

.own-message {
	flex-direction: row-reverse;
	justify-content: flex-start; /* 确保头像不会超出屏幕 */
}

.avatar {
	width: 40px;
	height: 40px;
	border-radius: 6px;
	overflow: hidden;
	margin: 0 8px;
	flex-shrink: 0; /* 防止头像被压缩 */
}

.avatar image {
	width: 100%;
	height: 100%;
	background-color: #ccc;
}

.avatar-default {
	width: 100%;
	height: 100%;
	background: linear-gradient(45deg, #007aff, #4cd964);
	display: flex;
	align-items: center;
	justify-content: center;
	color: white;
	font-weight: bold;
	font-size: 14px;
	border-radius: 6px;
}

.message-content {
	max-width: calc(100% - 80px); /* 为头像和边距预留空间 */
	min-width: 0; /* 确保内容可以正确折行 */
}

.message-bubble {
	background-color: #fff;
	padding: 12px 16px;
	border-radius: 8px;
	position: relative;
	word-wrap: break-word;
	box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.own-bubble {
	background-color: #95ec69;
}

.message-bubble text {
	font-size: 16px;
	color: #333;
	line-height: 1.4;
}

/* 聊天气泡箭头效果可以通过伪元素实现，这里简化处理 */
.message-bubble::before {
	content: '';
	position: absolute;
	top: 12px;
	left: -6px;
	width: 0;
	height: 0;
	border-style: solid;
	border-width: 6px 6px 6px 0;
	border-color: transparent #fff transparent transparent;
}

.own-message .message-bubble::before {
	left: auto;
	right: -6px;
	border-width: 6px 0 6px 6px;
	border-color: transparent transparent transparent #95ec69;
}

.input-section {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #f7f7f7;
	border-top: 1px solid #e5e5e5;
	padding: 8px 16px;
	padding-bottom: calc(8px + env(safe-area-inset-bottom));
	z-index: 1000;
}

.input-bar {
	display: flex;
	align-items: center;
	gap: 8px;
}

.voice-btn, .emoji-btn, .more-btn {
	width: 36px;
	height: 36px;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
}

.voice-btn:active, .emoji-btn:active, .more-btn:active {
	opacity: 0.6;
}

.voice-btn image, .emoji-btn image, .more-btn image {
	width: 24px;
	height: 24px;
	display: block;
}

.input-container {
	flex: 1;
	margin: 0 4px;
	position: relative;
	display: flex;
	align-items: center;
}

.message-input {
	flex: 1;
	height: 36px;
	background-color: #fff;
	border: 1px solid #e0e0e0;
	border-radius: 6px;
	padding: 0 12px;
	padding-right: 70px; /* 为发送按钮预留空间 */
	font-size: 16px;
	box-sizing: border-box;
}

.message-input:focus {
	border-color: #07c160;
	outline: none;
}

.send-btn {
	position: absolute;
	right: 4px;
	top: 50%;
	transform: translateY(-50%);
	background-color: #07c160;
	color: #fff;
	border-radius: 4px;
	padding: 4px 12px;
	font-size: 14px;
	font-weight: 500;
	line-height: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	min-width: 50px;
	height: 28px;
	box-sizing: border-box;
}

.send-btn:active {
	background-color: #06a652;
}

.send-btn text {
	color: #fff;
	font-size: 14px;
}
</style>